package com.cqrcb.cloud.utils;


import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.*;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import com.cqrcb.cloud.config.SftpConfig;
import com.cqrcb.cloud.properties.SftpServerProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @Author bq8023
 * @Date 21/5/9 19:57
 * @Version 1.0
 */
@Slf4j
public class SshUtil {
    private Connection connect;

    /**
     * 连接服务器并 执行shell脚本
     *
     * @param sshEntity ssh连接信息
     * @param shell     shell语句
     * @return shell执行结果
     * @throws IOException 读写异常
     */
    public StringBuilder exec(SftpServerProperties sshEntity, String shell,int waitMax) throws IOException {
        InputStream inputStream = null;
        StringBuilder result = new StringBuilder();
        try {
            // 认证登录信息
            if (this.login(sshEntity)) {
                // 登陆成功则打开一个会话
                Session session = connect.openSession();
                session.execCommand(shell);
                inputStream = session.getStdout();
                result = this.processStdout(inputStream,waitMax);
                connect.close();
            }
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
        }
        return result;
    }

    private boolean login(SftpServerProperties sshEntity) {
        connect = new Connection(sshEntity.getIp(), sshEntity.getPort());
        try {
            connect.connect();
            return connect.authenticateWithPassword(sshEntity.getUsername(), sshEntity.getPassword());
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    private StringBuilder processStdout(InputStream in,int maxLength) {
        ExecutorService executorService= Executors.newSingleThreadExecutor();
        Future<StringBuilder> future=executorService.submit(new SshCommand(in,maxLength));
        try {
            StringBuilder result=future.get(maxLength, TimeUnit.SECONDS);
            return result;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            log.error("超时了，原因:{}", e.getMessage());
        }
        return null;
    }


}

